package main

import (
	"fmt"
	"golang.org/x/tour/tree"
)

// Walk 步进 tree t 将所有的值从 tree 发送到 channel ch。
func Walk(t *tree.Tree, ch chan int) {
	//walkHelper(t, ch)
	//close(ch)
	var a func(t *tree.Tree)
	a = func(t *tree.Tree){
		if t == nil {
			return
		}
		a(t.Left)
		ch <- t.Value
		a(t.Right)
	}
	a(t)
	close(ch)
}


// Same 检测树 t1 和 t2 是否含有相同的值。
func Same(t1, t2 *tree.Tree) bool {
	ch1 := make(chan int)
	ch2 := make(chan int)

	go func() {
		Walk(t1, ch1)
	}()
	go func() {
		Walk(t2, ch2)
	}()

	for v1 := range ch1 {
		v2 := <-ch2
		if v1 != v2 {
			return false
		}
	}
	return true
}

func main() {
	t1 := tree.New(1)
	t2 := tree.New(1)
	fmt.Println("Same(tree.New(1), tree.New(1)): ", Same(t1, t2))

	t3 := tree.New(1)
	t4 := tree.New(2)
	fmt.Println("Same(tree.New(1), tree.New(2)): ", Same(t3, t4))
}